<template>
	<div class="table-box">
		<proTable
			ref="proTableRef"
			:columns="columns"
			:toolButton="true"
			:requestApi="competitionAchievementApi.GetCompetitionAchievementInfoApi"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<template #tableHeader>
				<el-button @click="handleDowloadExcelClick" :icon="Download" plain type="primary"> 导出成绩数据</el-button>
				<el-button v-if="false" @click="DowloadExcelClick" type="danger" :icon="Download" circle />
			</template>
			<template #operation="scope">
				<el-space wrap>
					<el-tag class="ml-2" @click="handleRegiseDetailClick(scope.row)" style="margin-right: 5px; cursor: pointer" type="info"
						>详情</el-tag
					>
				</el-space>
			</template>
			<template #competitionName="scope">
				{{ scope.row.competitionName }}
			</template>
		</proTable>
	</div>
</template>
<script lang="tsx" setup name="logs">
import { ref, reactive, computed, watch } from "vue";
import competitionAchievementApi from "@/api/modules/competitionAchievement";
import eventsSessionApi from "@/api/modules/eventsSession";
import api from "@/api/modules/paymentOrderInfo";
import { useRouter } from "vue-router";
import { convertTimeString } from "@/utils/util";
import { ColumnProps } from "@/components/ProTable/interface";
import proTable from "@/components/ProTable/index.vue";
import { Download } from "@element-plus/icons-vue";
import * as XLSX from "xlsx";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref();
const router = useRouter();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	Order: "",
	Sort: ""
});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 datalist && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.totalCount
	};
};
// 赛事选项
const getCompetitionsList = async () => {
	let { result } = await api.GetCompetitionsList();
	let { data, code } = result as any;
	if (code != 200) {
		return [];
	}
	data.unshift({ name: "全部", id: "" });
	return result;
};
const headerRender = (row: ColumnProps) => {
	return (
		<el-tooltip class="box-item" effect="dark" content={row.label} placement="top-start">
			{row.label}
		</el-tooltip>
	);
};
// 赛事项目下拉选择选项
const projectList = ref<any[]>([{ name: "全部", id: "" }]);
watch(
	() => proTableRef.value?.searchParam.competitionId,
	async () => {
		if (!proTableRef.value?.searchParam.competitionId) return;
		proTableRef.value.searchParam.competitionProjectId = "";
		proTableRef.value.searchParam.eventsSessionId = "";
		let { result } = await competitionAchievementApi.GetCompetionProjectListByCompetionIdApi(
			proTableRef.value.searchParam.competitionId
		);
		projectList.value.length = 0;
		projectList.value.push(...[{ name: "全部", id: "" }, ...result.data]);
	}
);
// 赛事节点下拉选择选项
const compotitionNode = ref<any[]>([{ matchType: "全部", id: "" }]);
watch(
	() => proTableRef.value?.searchParam.competitionProjectId,
	async () => {
		if (!proTableRef.value?.searchParam.competitionProjectId) return;
		proTableRef.value.searchParam.eventsSessionId = "";
		let { result } = await eventsSessionApi.GetEventsSessionListApi(proTableRef.value.searchParam.competitionProjectId);
		if (!result.data) return;
		compotitionNode.value.length = 0;
		compotitionNode.value.push(...[{ matchType: "全部", id: "" }, ...result.data]);
	}
);
// 表格配置项
const columns = computed((): Partial<ColumnProps>[] => {
	let data: Partial<ColumnProps>[] = [
		{
			prop: "competitionName",
			label: "赛事名称",
			headerRender
		},
		{
			prop: "competitionProjectName",
			label: "比赛项目",
			headerRender,
			render: scope => {
				return <>{scope.row.competitionProjectName}</>;
			}
		},
		{
			prop: "competitionId",
			label: "赛事名称",
			headerRender,
			isShow: false,
			enum: getCompetitionsList,
			search: { el: "select", props: { filterable: true }, defaultValue: "" },
			fieldNames: { label: "name", value: "id" }
		},
		{
			prop: "competitionProjectId",
			label: "比赛项目",
			isShow: false,
			enum: projectList.value,
			search: { el: "select", props: { filterable: true }, defaultValue: "" },
			fieldNames: { label: "name", value: "id" }
		},
		{ prop: "projectTypeName", headerRender, label: "项目类型", isShow: false },
		{ prop: "gameTypeName", headerRender, label: "比赛类型" },
		{ prop: "contestantOrTeam", headerRender, label: "参赛者/团队" },
		{ prop: "competitionNumberPosition", headerRender, label: "比赛号位" },
		{
			prop: "competitionNode",
			label: "比赛节点",
			headerRender,
			render: scope => {
				return <>{scope.row.competitionNode}</>;
			}
		},
		{
			prop: "eventsSessionId",
			label: "比赛节点",
			isShow: false,
			enum: compotitionNode.value,
			search: { el: "select", props: { filterable: true }, defaultValue: "" },
			fieldNames: { label: "matchType", value: "id" }
		},
		{ prop: "achievementCircle", headerRender, label: "成绩圈" },
		{
			prop: "achievementTime",
			headerRender,
			label: "总用时",
			render: scope => {
				return <>{convertTimeString((parseFloat(scope.row.achievementTime) - parseFloat(scope.row.buckleTime)).toFixed(3))}</>;
			}
		},
		{ prop: "actualLap", headerRender, label: "实际跑圈" },
		{ prop: "buckleRing", headerRender, label: "扣圈" },
		{ prop: "lastLapTime", headerRender, label: "最后一圈时间", isShow: false },
		{ prop: "buckleTime", headerRender, label: "加时" },
		{ prop: "missingMark", headerRender, label: "漏标" },
		{ prop: "yellowCard", headerRender, label: "黄牌" },
		{ prop: "redCard", headerRender, label: "红牌" },
		{
			prop: "score",
			headerRender,
			label: "总成绩",
			render: scope => {
				return (
					<>
						{(scope.row.achievementCircle < 0 ? 0 : scope.row.achievementCircle) +
							"圈" +
							"" +
							convertTimeString(scope.row.achievementTime)}
					</>
				);
			}
		},
		{ prop: "competitionRanking", headerRender, label: "比赛排名" },
		{ prop: "competitionStartTime", headerRender, label: "比赛时间", isShow: false },
		{ prop: "competitionVenue", headerRender, label: "比赛地点", isShow: false },
		{
			prop: "KeywordName",
			label: "关键字",
			isShow: false,
			search: { el: "input", props: { placeholder: "请输入赛事名称/用户姓名/比赛项目" } }
		},
		{ prop: "operation", label: "操作", width: 100, fixed: "right" }
	];
	return data;
});
// 报名详情
const handleRegiseDetailClick = (row: any) => {
	router.push("/competition/score/detail?id=" + row.id);
};
// 下载成绩
const handleDowloadExcelClick = () => {
	competitionAchievementApi
		.DownloadEventsSessionCompetitionAchievementExcelApi({
			PageIndex: proTableRef.value.pageable.pageIndex,
			PageSize: proTableRef.value.pageable.pageSize,
			Order: "",
			Sort: "",
			EventsSessionId: ""
		})
		.then(res => {
			let { data } = res.result;
			let url = import.meta.env.VITE_APP_BASE_URL + data.url;
			downloadFile(url);
		});
};
const downloadFile = (url: string) => {
	let arr = url.split("/");
	let filename = arr[arr.length - 1];
	const link = document.createElement("a");
	link.href = url;
	link.download = filename;
	link.style.display = "none";
	document.body.appendChild(link);
	link.click();
};
const DowloadExcelClick = () => {
	// exportExcelByTable(proTableRef.value.element);
	const tableData = JSON.parse(JSON.stringify(proTableRef.value?.tableData));
	let head: any = {};
	columns.value.forEach(i => {
		head[i.prop!] = i.label!;
	});
	const list = tableData.map((item: any) => {
		const obj: any = {};
		for (const k in item) {
			if (head[k]) {
				obj[head[k]] = item[k];
			}
		}
		return obj;
	});
	// 创建工作表
	const ws = XLSX.utils.json_to_sheet(list);
	// 创建工作簿
	const wb = XLSX.utils.book_new();
	// 将工作表放入工作簿中
	XLSX.utils.book_append_sheet(wb, ws, "data");
	// 设置自适应列宽
	const columnsList = Object.keys(tableData[0]);
	const colWidth = columnsList.map(col => {
		return { wch: col.length + 5 };
	});
	ws["!cols"] = colWidth;
	// 合并相同的行列
	const range = XLSX.utils.decode_range(ws["!ref"]!);
	for (let i = range.s.r + 1; i <= range.e.r; i++) {
		for (let j = range.s.c; j <= range.e.c; j++) {
			const cell1 = ws[XLSX.utils.encode_cell({ r: i - 1, c: j })];
			const cell2 = ws[XLSX.utils.encode_cell({ r: i, c: j })];
			if (cell1 && cell2 && cell1.v === cell2.v) {
				if (!ws["!merges"]) ws["!merges"] = [];
				ws["!merges"].push({ s: { r: i - 1, c: j }, e: { r: i, c: j } });
			}
		}
	}
	// 生成文件并下载
	XLSX.writeFile(wb, "test.xlsx");
};
</script>
